<template>
	<view class="infoview">
		<view class="topBar">
			<hx-navbar :background-color="navbarConfig.background" :fixed="true" :back="true" transparent="show" :color="navbarConfig.color"
			 title="个人信息"></hx-navbar>
		</view>

		<view class="form-box">
			<u-form :model="form" ref="uForm">
				<u-form-item label-width="150" label="用户名:" prop="name">
					<u-input v-model="form.name" type="text" placeholder="请输入用户名" />
				</u-form-item>
				<u-form-item label-width="150" label="昵称:" prop="nickName">
					<u-input v-model="form.nickName" type="text" placeholder="请输入昵称" />
				</u-form-item>
				<u-form-item label-width="150" label="头像:">
					<uni-upimg @change="getImageInfo" :upimg_preview="imageUrl" :upload_count="1"></uni-upimg>
				</u-form-item>
			</u-form>
		</view>

		<view class="fiexd-btm">
			<u-button class="custom-style" type="primary" @tap="submit">保存</u-button>
		</view>
	</view>
</template>

<script>
	import uniUpimg from '@/components//uni-upimg/uni-upimg.vue'
	import {
		mapState
	} from 'vuex'
	export default {
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		components: {
			uniUpimg
		},
		data() {
			return {
				form: {
					name: '',
					nickName: '',
					imageUrl: ''
				},
				imageUrl: [],
				rules: {
					name: [{
						required: true,
						min: 2,
						message: '姓名不能少于2个字符',
						trigger: 'change'
					}],
					nickName: [{
						required: true,
						min: 2,
						message: '昵称不能少于2个字符',
						trigger: 'change'
					}]
				}
			}
		},
		onLoad() {
			this.form.imageUrl = this.userInfo.imageUrl || ''
			this.form.nickName = this.userInfo.nickName || ''
			this.form.name = this.userInfo.name || ''
			this.imageUrl = this.userInfo.imageUrl ? [{
				path: this.userInfo.imageUrl
			}] : []
		},
		computed: {
			...mapState(['userInfo'])
		},
		methods: {
			getImageInfo(e) {
				this.imageUrl = e
				this.form.imageUrl = this.imageUrl[0]
			},
			submit(e) {
				this.$refs.uForm.validate(valid => {
					if (!valid) {
						console.log('验证失败');
						return
					} else {
						this.$api.request('POST', '/api/user/updateUserInfoById', this.form).then(res => {
							this.$api.msg('保存成功')
							this.userInfo.imageUrl = this.form.imageUrl
							this.userInfo.nickName = this.form.nickName
							this.userInfo.name = this.form.name
							this.$store.commit('login', this.userInfo)
							setTimeout(() => {
								this.$api.prePage().loadData()
								uni.navigateBack()
							}, 500)
						})
					}
				});
			}
		}
	}
</script>

<style lang="less">
</style>
